﻿using System;
using SuperSocket.Common;
using SuperSocket.Facility.Protocol;

namespace AccelerateSensor.SocketServer.Server
{
    /// 客户端向服务器发送数据协议
    /// +----------+------------+-------+-------+-------+-------+----------------+--------------+
    /// |  0xFFFE  |    Len     | Data1 | Data2 | Data3 | Data4 |      Data      |     CKS      |
    /// | (Header) |  (Length)  | (MAC) | (CN1) | (CN2) | (Len) | (Message Body) | (Check Code) |
    /// |    (2)   |    (2)     |  (8)  |  (1)  |  (2)  |  (2)  |      (Len)     |     (1)      |
    /// +----------+------------+-------+-------+-------+-------+----------------+--------------+

    public class MyReceiveFilter : FixedHeaderReceiveFilter<MyRequestInfo>
    {
        /// +-------+---+-------------------------------+
        /// |request| l |                               |
        /// | name  | e |       request body            |
        /// |  (0)  | n |                               |
        /// |       |(4)|                               |
        /// +-------+---+-------------------------------+

        private const int HeaderSize = 4; //Header总长度
        private const int HeaderLenOffset = 0; //长度offset

        public MyReceiveFilter() : base(HeaderSize)
        {

        }

        protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
        {
            var lenCount = HeaderSize - HeaderLenOffset;
            var lenBuffer = new byte[lenCount];
            Buffer.BlockCopy(header, offset + HeaderLenOffset, lenBuffer, 0, lenCount);
            Array.Reverse(lenBuffer);
            return BitConverter.ToInt32(lenBuffer, 0);
        }

        protected override MyRequestInfo ResolveRequestInfo(ArraySegment<byte> header,
            byte[] bodyBuffer, int offset, int length)
        {
            return new MyRequestInfo(header.Array.CloneRange(header.Offset, HeaderSize),
                bodyBuffer.CloneRange(offset, length));
        }
    }
}
